package com.liao.view.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoadDataAsyncTask extends AsyncTask<String, Void, String> {
    private Context context;
    private GetDataCallBack getDataCallBack;
    private ProgressDialog progressDialog;

    public LoadDataAsyncTask(Context context, GetDataCallBack getDataCallBack) {
        this.context = context;
        this.getDataCallBack = getDataCallBack;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("正在加载...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request build = new Request.Builder()
                    .url(strings[0])
                    .build();
            Response execute = client.newCall(build).execute();
            return execute.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        progressDialog.dismiss();
        getDataCallBack.getDataCallBack(s);
    }

    public interface GetDataCallBack {
        void getDataCallBack(String data);
    }
}
